import JoyStick from "./JoyStick";
import { EVT_PLAYER_SET_WEAPON_P } from "./Core/AppEvent";
import { dispatchEvent } from "./Managers/EventManager";

const {ccclass, property} = cc._decorator;


@ccclass
export default class AttackJoyStick extends JoyStick {
    @property(cc.Node)
    dotSprite: cc.Node = null;
    
    startPoint = new cc.Vec2(0,0);

    onLoad(){
    }

    public onTouchStart(event) {
        let location = event.getLocation();
        let winSize = cc.view.getVisibleSize();
        this.node.position = new cc.Vec3(location.x - winSize.width/2, location.y - winSize.height/2, 0);
        this.startPoint = location;
    }

    public onTouchMove(event) {
        let location = event.getLocation();
        let offsetX = location.x - this.startPoint.x;
        let offsetY = location.y - this.startPoint.y;
        let contentSize = this.node.getContentSize();
        let length = location.sub(cc.v2(this.startPoint)).mag(); 
        let p = location.sub(cc.v2(this.startPoint)).normalize();
        let radius = contentSize.width/2
        if(length <= radius){
            this.dotSprite.position = new cc.Vec3(offsetX, offsetY, 0);
        }else{
            this.dotSprite.position = new cc.Vec3(radius*p.x, radius*p.y, 0);
        }
        
        let radian = Math.acos(offsetX / Math.sqrt(offsetX*offsetX+offsetY*offsetY));
        let angle = cc.misc.radiansToDegrees(radian);
        let scalex = offsetX > 0 ? 1 : -1;
        if(offsetY > 0 && offsetX < 0){
            angle = -angle;  
        }
        if(offsetY < 0 && offsetX > 0){
            angle = -angle;  
        }
        if(scalex == -1){
            angle -= 180;
        }
        dispatchEvent(EVT_PLAYER_SET_WEAPON_P, {p, angle, scalex});

    }

    public onTouchEnd(event) {
        this.dotSprite.position = cc.Vec3.ZERO;
        dispatchEvent(EVT_PLAYER_SET_WEAPON_P, { p: cc.v3(0,0,0)});
    }

}
